//下载cnpm install axios --save
//对axios的二次封装
import axios from "axios"
export default function ajax(url = "", params = {}, type = "get") {
    //1 定义一个变量
    var promise
    return new Promise((resolve, reject) => {
        //2 判断一下请求的方式
        if (type == "get") {
            let paramsStr = ""
            Object.keys(params).forEach(key => {
                paramsStr += key + "=" + params[key] + "&"
            })
            // console.log(paramsStr); //page=1&size=10&
            if (paramsStr != "") {  //如果条件成立说明params肯定已经传参了
                paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf("&"))   //page=1&size=10
            }
            url += "?" + paramsStr  // http://localhost:3000/userlist?page=1&size=10
            promise = axios.get(url)
        } else if (type == "post") {
            promise = axios.post(url, params)
        }
        promise.then(response => {
            resolve(response.data)  //成功
        }).catch(err => {
            reject(err)  //失败
        })
    })
}


// 使用

//http://localhost:3000/userlist?page=1&size=10
// ajax(
//     url: "http://localhost:3000/userlist",
//     type: "get",
//     params: {page:1,size:10}
// )